package com.ruoyi.web.controller.qcsystem;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.handler.AbstractRowWriteHandler;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.qcsystem.domain.entity.QualityFistConfirmation;
import com.ruoyi.qcsystem.domain.entity.QualityMoldConfirmation;
import com.ruoyi.qcsystem.service.QcFistDataService;
import com.ruoyi.qcsystem.service.QcMoldDataService;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileSystemUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("qcFistSystem")
public class QCFistSystemController {

    @Value("${ruoyi.profile}")
    private String uploadPath;

    @Autowired
    QcFistDataService qcDataService;
    Integer lineId;
    String startTime;
    String endTime;
    String mpn;
    String lot;

    @GetMapping("list")
    PageInfo<QualityFistConfirmation> qualityConfirmationList(@RequestParam(defaultValue="6")Integer lineId,
                                                              @RequestParam(defaultValue="1")Integer pageNum,
                                                              @RequestParam(defaultValue="10")Integer pageSize,
                                                              @RequestParam(defaultValue="")String startTime,
                                                              @RequestParam(defaultValue="")String endTime,
                                                              @RequestParam(defaultValue="")String mpn,
                                                              @RequestParam(defaultValue="")String lot
    ){

        if (!startTime.isEmpty() && !endTime.isEmpty()){
            if(startTime.equals(endTime)){
                try {
                    DateTimeFormatter  ft = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                    LocalDate date = LocalDate.parse(endTime,ft);
                    LocalDate nextDay  = date.plusDays(1);
                    endTime = nextDay.format(ft);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        this.lineId = lineId==null?1:lineId;
        this.startTime = startTime==null?"":startTime;
        this.endTime = endTime==null?"":endTime;
        this.mpn = mpn==null?"":mpn;
        this.lot = lot==null?"":lot;
        return qcDataService.qualityConfirmationList(lineId,pageNum,pageSize,startTime,endTime,mpn,lot);
    }


    @PostMapping("addQualityConfirmation")
    int addQualityConfirmation(@Validated  @RequestBody QualityFistConfirmation qualityConfirmation){
        Long userId = SecurityUtils.getLoginUser().getUserId();
        String userName = SecurityUtils.getLoginUser().getUsername();
        qualityConfirmation.setUserId(userId);
        qualityConfirmation.setAdmit(userName);
        return qcDataService.addQualityConfirmation(qualityConfirmation);
    }

    @DeleteMapping("deleteQualityConfirmation")
    int deleteQualityConfirmation(@RequestParam Long qcId){
        return qcDataService.deleteQualityConfirmation(qcId);
    }

    @GetMapping("getMachineNumber")
    int getMachineNumber(@RequestParam Integer lineId){
        long processId=1;
        return qcDataService.getMachineNumber(lineId,processId);
    }

    @PostMapping("updateQualityConfirmation")
    int updateQualityConfirmation(@Validated @RequestBody QualityFistConfirmation qualityConfirmation){
        return qcDataService.updateQualityConfirmation(qualityConfirmation);
    }


    @PostMapping("/handleExport")
    public void export(HttpServletResponse response) throws IOException {
        // 1. Set response headers
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("UTF-8");
        String fileName = URLEncoder.encode("样品数据", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        // 2. Get data
        List<QualityFistConfirmation> dataList = qcDataService.qualityConfirmationList(lineId,startTime,endTime,mpn,lot);

        // 3. Create Excel writer with custom handler
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), QualityFistConfirmation.class)
                .registerWriteHandler(new AbstractRowWriteHandler() {
                    @Override
                    public void afterRowDispose(WriteSheetHolder writeSheetHolder,
                                                WriteTableHolder writeTableHolder,
                                                Row row,
                                                Integer relativeRowIndex,
                                                Boolean isHead) {
                        // Add timestamp after last data row
                        if (!isHead && relativeRowIndex != null && relativeRowIndex == dataList.size() - 1) {
                            Sheet sheet = writeSheetHolder.getSheet();
                            int lastRowNum = sheet.getLastRowNum();
                            // 创建当前时间
                            Row timeRow = sheet.createRow(lastRowNum + 1);
                            String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                            timeRow.createCell(0).setCellValue("导出时间:"+format);
                            // Merge cells if needed (columns 0-7)
                            sheet.addMergedRegion(new CellRangeAddress(
                                    lastRowNum + 1, // first row
                                    lastRowNum + 1, // last row
                                    0,              // first column
                                    7               // last column
                            ));
                        }
                    }
                })
                .build();

        // 4. Write data
        WriteSheet writeSheet = EasyExcel.writerSheet("样品列表").build();
        excelWriter.write(dataList, writeSheet);
        excelWriter.finish();
    }

    @PostMapping("/upload")
    public List<String> uploadFile(@RequestParam("files") MultipartFile[] files) {
        List<String> urls = new ArrayList<>();
        for (int i=0;i<files.length;i++) {
            MultipartFile file = files[i];
            // 1. 检查是否为占位符文件
            if (isPlaceholderFile(file)) {
                urls.add(""); // 添加空字符串保持索引对应
                continue;
            }
            // 1. 检查文件是否为空
            if (file.isEmpty()) {
                urls.add(""); // 添加空字符串保持索引对应
                continue;
            }

            try (InputStream inputStream = file.getInputStream()) {  // 使用try-with-resources确保流关闭
                // 2. 生成唯一文件名
                String fileName = generateUniqueFileName(file.getOriginalFilename());

                // 3. 确保目标目录存在
                File uploadDir = new File(uploadPath);
                if (!uploadDir.exists() && !uploadDir.mkdirs()) {
                    return urls;
                }

                // 4. 创建目标路径（修复路径分隔符问题）
                Path filePath = Paths.get(uploadPath, fileName);

                // 5. 保存文件（使用REPLACE_EXISTING选项）
                Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING);

                // 6. 记录访问URL（使用虚拟路径而非物理路径）
                String url = "/profile/" + fileName;  // 重要：使用Web访问路径
                urls.add(url);
            } catch (IOException e) {
                // 7. 处理异常并清理临时文件
                FileSystemUtils.deleteRecursively(new File(System.getProperty("java.io.tmpdir")));
                return urls;
            } finally {
                // 8. 确保释放文件资源（解决"Cannot delete"错误的核心）
                try {
                    if (!file.isEmpty()) {
                        // 强制释放文件资源
                        file.transferTo(new File("NUL"));  // Windows系统
                        // 对于Linux/Mac使用：file.transferTo(new File("/dev/null"));
                    }
                } catch (IOException ex) {

                }
            }
        }
        return  urls;
    }

    // 生成唯一文件名
    private String generateUniqueFileName(String originalFilename) {
        String extension = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }

        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String uuid = UUID.randomUUID().toString().replace("-", "").substring(0, 8);

        return timeStamp + "_" + uuid + extension;
    }

    /**
     * 判断是否为占位符文件
     */
    private boolean isPlaceholderFile(MultipartFile file) {
        try {
            if (file == null || file.isEmpty()) {
                return true;
            }

            // 检查文件名特征
            String filename = file.getOriginalFilename();
            if (filename != null &&
                    (filename.equals("placeholder.txt") ||
                            filename.startsWith("empty_") ||
                            filename.endsWith("_placeholder"))) {
                return true;
            }

            // 检查文件大小（占位符文件通常很小）
            if (file.getSize() <= 50) {
                // 检查文件内容
                if (file.getSize() > 0) {
                    String content = new String(file.getBytes(), StandardCharsets.UTF_8);
                    if (content.contains("EMPTY_FILE_PLACEHOLDER") ||
                            content.contains("PLACEHOLDER") ||
                            content.trim().isEmpty()) {
                        return true;
                    }
                }
                return true;
            }

            return false;

        } catch (IOException e) {
            // 如果读取失败，当作占位符处理
            return true;
        }
    }


}
